import { useCallback, useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import './Chat.css';
import ChartCard from '@/components/ChartCard';
import statisticsApi from '@/apis/statisticsApi';
import { Tabs } from 'react-vant';

interface ChartDataItem {
  name?: string;
  value?: number;
  time?: string;
  sales?: number;
  category?: string;
}

interface ResponseChartStatisticsDto {
  chart1Data: ChartDataItem[];
  chart2Data: ChartDataItem[];
  chart3Data: ChartDataItem[];
  chart4Data: ChartDataItem[];
}

const tabItems = [
  { label: '今日', key: 'date' },
  { label: '本周', key: 'week' },
  { label: '本月', key: 'month' },
  { label: '本年', key: 'year' },
];

const Chat: React.FC = () => {
  const [statistics, setStatistics] = useState<ResponseChartStatisticsDto | null>(null);
  const [activeTab, setActiveTab] = useState<string>('date');

  // 使用useRef保存图表实例
  const salesChartRef = useRef<echarts.ECharts | null>(null);
  const productChartRef = useRef<echarts.ECharts | null>(null);
  const orderChartRef = useRef<echarts.ECharts | null>(null);
  const unitPriceChartRef = useRef<echarts.ECharts | null>(null);

  // DOM引用
  const saleTrendChartRef = useRef<HTMLDivElement>(null);
  const typeCategoryRankingChartRef = useRef<HTMLDivElement>(null);
  const orderStatusDistributionChartRef = useRef<HTMLDivElement>(null);
  const orderPriceDistributionChartRef = useRef<HTMLDivElement>(null);

  // 初始化图表配置
  const initChart = (
    chartRef: React.MutableRefObject<echarts.ECharts | null>,
    chartDomRef: React.RefObject<HTMLDivElement | null>,
    option: echarts.EChartsOption
  ) => {
    if (!chartRef.current && chartDomRef.current) {
      const chart = echarts.init(chartDomRef.current);
      chartRef.current = chart;

      const emptyOption: echarts.EChartsOption = {
        ...option,
      };
      chart.setOption(emptyOption);
    }
    return chartRef.current;
  };

  // 初始化所有图表
  const initAllCharts = () => {
    // 销售趋势图
    initChart(salesChartRef, saleTrendChartRef, {
      title: { text: '销售趋势', left: 'center' },
      tooltip: {},
      xAxis: { type: 'category', data: [] },
      yAxis: { type: 'value' },
      series: [
        {
          data: [],
          type: 'line',
          smooth: true,
          areaStyle: {},
          color: '#1890ff',
        },
      ],
    });

    // 商品销售柱状图
    initChart(productChartRef, typeCategoryRankingChartRef, {
      title: { text: '品类销售排行', left: 'center' },
      tooltip: {},
      xAxis: { type: 'category', data: [] },
      yAxis: { type: 'value' },
      series: [
        {
          type: 'bar',
          data: [],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 1, color: '#1882ff' },
            ]),
          },
        },
      ],
    });

    // 订单状态饼图
    initChart(orderChartRef, orderStatusDistributionChartRef, {
      title: { text: '订单状态分布', left: 'center' },
      tooltip: { trigger: 'item' },
      series: [
        {
          type: 'pie',
          radius: '60%',
          data: [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    });

    // 订单总价分布饼图
    initChart(unitPriceChartRef, orderPriceDistributionChartRef, {
      title: { text: '订单总价分布', left: 'center' },
      tooltip: { trigger: 'item' },
      series: [
        {
          type: 'pie',
          radius: '60%',
          data: [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    });
  };

  // 更新图表数据
  const updateCharts = (data: ResponseChartStatisticsDto | null) => {
    if (!data) return;

    // 更新销售趋势图
    if (data.chart1Data?.length > 0) {
      salesChartRef.current?.setOption({
        xAxis: { data: data.chart1Data.map((d) => d.time) },
        series: [{ data: data.chart1Data.map((d) => d.sales) }],
      });
    }

    // 更新商品销售柱状图
    if (data.chart2Data?.length > 0) {
      productChartRef.current?.setOption({
        xAxis: { data: data.chart2Data.map((d) => d.category) },
        series: [{ data: data.chart2Data.map((d) => d.sales) }],
      });
    }

    // 更新订单状态饼图
    orderChartRef.current?.setOption({
      series: [{ data: data.chart3Data || [] }],
    });

    // 更新订单总价分布饼图
    unitPriceChartRef.current?.setOption({
      series: [{ data: data.chart4Data }],
    });
  };

  const fetchData = async (activeTab: string) => {
    const res = await statisticsApi.getChartSstatistics(activeTab);
    if (res.status >= 0) {
      setStatistics(res.data);
    }
  };

  useEffect(() => {
    fetchData(activeTab);
    const interval = setInterval(() => fetchData(activeTab), 15000);
    return () => {
      clearInterval(interval);
    };
  }, [activeTab]);

  useEffect(() => {
    initAllCharts();

    const resizeHandler = () => {
      salesChartRef.current?.resize();
      productChartRef.current?.resize();
      orderChartRef.current?.resize();
      unitPriceChartRef.current?.resize();
    };

    window.addEventListener('resize', resizeHandler);

    return () => {
      window.removeEventListener('resize', resizeHandler);
      salesChartRef.current?.dispose();
      productChartRef.current?.dispose();
      orderChartRef.current?.dispose();
      unitPriceChartRef.current?.dispose();
    };
  }, []);

  useEffect(() => {
    updateCharts(statistics);
  }, [statistics]);

  return (
    <>
      <Tabs type="capsule" onChange={(at: string | number) => setActiveTab(at as string)}>
        {tabItems.map((item) => (
          <Tabs.TabPane key={item.key} name={item.key} title={item.label}></Tabs.TabPane>
        ))}
      </Tabs>
      <ChartCard ref={saleTrendChartRef}></ChartCard>
      <ChartCard ref={typeCategoryRankingChartRef}></ChartCard>
      <ChartCard ref={orderStatusDistributionChartRef}></ChartCard>
      <ChartCard ref={orderPriceDistributionChartRef}></ChartCard>
    </>
  );
};

export default Chat;
